<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\helpers\VarDumper;
use yii\helpers\ArrayHelper;

use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;

use app\models\ScoreModel;

class ScoreController extends Controller
{

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index');
    }
    public function actionAddscore()
    {
        $openid = Yii::$app->request->post('openid');
        $userinfo = Yii::$app->request->post('userinfo');
        $score = Yii::$app->request->post('score');

        Yii::$app->db->createCommand()->insert('score',[
            'openid'=>$openid,
            'userinfo'=>$userinfo,
            'score'=>$score
            ])->execute();

        $data = array(
            'code' => 0,
            'message' => '新增成功',
            'result' => new \stdClass 
        );
        

        $json = json_encode($data);
        return $json;
    }
    public function actionGetscore()
    {
        $model = ScoreModel::find()
        ->select('openid,userinfo,sum(score) as score_sum')
            ->where(['score' => 10])
            ->groupBy(['openid'])
            ->orderBy([
                'score_sum' => SORT_DESC,
                'id' => SORT_ASC
            ])
            ->asArray()
            ->all();

        $data = array(
            'code' => 0,
            'message' => '',
            'result' => $model
        );

        $json = json_encode($data);
        return $json;
    }
    public function actionGetscorebyopenid()
    {
        $openid = Yii::$app->request->post('openid');
        $model = ScoreModel::find()
            ->where(['openid' => $openid])
            ->orderBy('id DESC')
            ->asArray()
            ->one();

        $data = array(
            'code' => 0,
            'message' => '',
            'result' => $model
        );

        $json = json_encode($data);
        return $json;
    }
}
